class Solution:
    def removeBoxes(self, boxes: list) -> int:
        def func(boxes, i, j, k, dp):
            if j < i:
                return 0
            if dp[i][j][k] > 0:
                return dp[i][j][k]
            res = (k + 1) * (k + 1) + func(boxes, i + 1, j, 0, dp)
            for m in range(i + 1, j + 1):
                if boxes[m] == boxes[i]:
                    res = max(res,
                              func(boxes, i + 1, m - 1, 0, dp) +
                              func(boxes, m, j, k + 1, dp))

            dp[i][j][k] = res
            return res

        n = len(boxes)
        dp = [[[0] * n for i in range(n)] for _ in range(n)]

        return func(boxes, 0, len(boxes) - 1, 0, dp)
